#!/usr/bin/env node
/**
 * 手动合并批次文件生成最终知识库
 * 用于修复保存阶段失败的情况
 */

const fs = require('fs');
const path = require('path');

const OUTPUT_DIR = path.join(__dirname, '../core/knowledge');
const tempBatchDir = path.join(OUTPUT_DIR, 'temp_batches');

if (!fs.existsSync(tempBatchDir)) {
    console.error('❌ 批次文件目录不存在');
    process.exit(1);
}

// 读取批次文件
const batchFiles = fs.readdirSync(tempBatchDir)
    .filter(f => f.startsWith('batch-') && f.endsWith('.json'))
    .map(f => {
        const match = f.match(/batch-(\d+)\.json/);
        return match ? { file: f, number: parseInt(match[1]) } : null;
    })
    .filter(f => f !== null)
    .sort((a, b) => a.number - b.number);

console.log(`📦 找到 ${batchFiles.length} 个批次文件，开始合并保存...`);

// 按类别合并和保存
const categories = [
    'classes', 'functions', 'headerDependencies', 'buildGnRelations', 
    'buildGnExternalDeps', 'testPatterns', 'testFileDependencies',
    'mockPatterns', 'functionCoveragePatterns', 'functionCallRelations',
    'testFunctionStrategies', 'branchCoveragePatterns', 'coverageQualityMetrics',
    'napiPatterns', 'ndkPatterns'
];

let savedParts = 0;
let totalSize = 0;

async function mergeAndSave() {
    for (const category of categories) {
        try {
            const partFile = path.join(OUTPUT_DIR, `oh-knowledge-base-${category}.json`);
            const writeStream = fs.createWriteStream(partFile, { encoding: 'utf-8' });
            
            // 写入数组开始
            writeStream.write('[\n');
            
            let firstItem = true;
            let itemCount = 0;
            
            // 遍历所有批次文件，提取该类别数据
            for (const batchFile of batchFiles) {
                try {
                    const batchPath = path.join(tempBatchDir, batchFile.file);
                    const batchData = JSON.parse(fs.readFileSync(batchPath, 'utf-8'));
                    const items = batchData[category] || [];
                    
                    for (const item of items) {
                        if (!firstItem) {
                            writeStream.write(',\n');
                        }
                        writeStream.write('  ' + JSON.stringify(item));
                        firstItem = false;
                        itemCount++;
                    }
                } catch (error) {
                    console.warn(`   ⚠️ 处理批次 ${batchFile.number} 的 ${category} 失败: ${error.message}`);
                }
            }
            
            // 写入数组结束
            writeStream.write('\n]');
            writeStream.end();
            
            await new Promise((resolve, reject) => {
                writeStream.on('finish', () => {
                    const fileSize = fs.statSync(partFile).size;
                    totalSize += fileSize;
                    savedParts++;
                    console.log(`   ✓ ${category}: ${(fileSize / 1024 / 1024).toFixed(2)} MB (${itemCount} 条记录)`);
                    resolve();
                });
                writeStream.on('error', (err) => reject(err));
            });
        } catch (error) {
            console.error(`   ✗ ${category} 保存失败: ${error.message}`);
        }
    }
    
    // 读取第一个批次文件的metadata和stats
    try {
        const firstBatch = JSON.parse(fs.readFileSync(path.join(tempBatchDir, batchFiles[0].file), 'utf-8'));
        const metadata = {
            version: '2.1.0',
            generatedAt: new Date().toISOString(),
            ohRoot: process.env.OH_ROOT || '/home/yaoruozi/openharmony/code1028',
            stats: {
                totalFiles: batchFiles.length * 1000, // 估算
                scanTimeMs: 0
            }
        };
        
        const metadataFile = path.join(OUTPUT_DIR, 'oh-knowledge-base-metadata.json');
        fs.writeFileSync(metadataFile, JSON.stringify(metadata, null, 2), 'utf-8');
        savedParts++;
        totalSize += fs.statSync(metadataFile).size;
        console.log(`   ✓ metadata: ${(fs.statSync(metadataFile).size / 1024 / 1024).toFixed(2)} MB`);
    } catch (error) {
        console.error(`   ✗ metadata 保存失败: ${error.message}`);
    }
    
    // 保存空的bestPractices（避免缺失）
    try {
        const bestPracticesFile = path.join(OUTPUT_DIR, 'oh-knowledge-base-bestPractices.json');
        fs.writeFileSync(bestPracticesFile, JSON.stringify([], null, 2), 'utf-8');
        savedParts++;
        totalSize += fs.statSync(bestPracticesFile).size;
        console.log(`   ✓ bestPractices: ${(fs.statSync(bestPracticesFile).size / 1024 / 1024).toFixed(2)} MB`);
    } catch (error) {
        console.error(`   ✗ bestPractices 保存失败: ${error.message}`);
    }
    
    console.log(`\n✅ 合并完成（${savedParts} 个部分，总计 ${(totalSize / 1024 / 1024).toFixed(2)} MB）`);
    
    // 创建索引文件
    const indexFile = path.join(OUTPUT_DIR, 'oh-knowledge-base-index.json');
    const index = {
        version: '2.1.0',
        generatedAt: new Date().toISOString(),
        parts: categories.map(key => ({
            name: key,
            file: `oh-knowledge-base-${key}.json`
        })).concat([
            { name: 'metadata', file: 'oh-knowledge-base-metadata.json' },
            { name: 'bestPractices', file: 'oh-knowledge-base-bestPractices.json' }
        ]),
        stats: {},
        totalSizeMB: (totalSize / 1024 / 1024).toFixed(2)
    };
    
    fs.writeFileSync(indexFile, JSON.stringify(index, null, 2), 'utf-8');
    console.log(`✅ 索引文件已创建: ${indexFile}`);
    
    console.log('\n🎉 知识库合并完成！');
}

mergeAndSave().catch(err => {
    console.error('❌ 合并失败:', err);
    process.exit(1);
});


